/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2023-09-28     SenyPC       the first version
 */
#include "slave_uart.h"

#define DBG_TAG "slave_uart"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>

struct device_uart_type _dev_uart;


static int dev_uart_init( void ) {
    int ret = 0;
    _dev_uart.devname = SERIAL_UART_NAME;
    _dev_uart.baudrate = UART_BAUD_DEFAULT;
    _dev_uart.bytesize = UART_BYTESIZE_DEFAULT;
    _dev_uart.parity = UART_PARITY_DEFAULT;
    _dev_uart.stopbits = UART_STOPBITS_DEFAULT;

    _dev_uart.dev = modbus_rtu(MODBUS_SLAVE);
    if(NULL == _dev_uart.dev) {
        LOG_E("dev_uart create error.");
        return -MODBUS_RT_ERROR;
    }
    if(MODBUS_RT_EOK != (ret = modbus_rtu_set_serial(_dev_uart.dev, _dev_uart.devname, _dev_uart.baudrate,
            _dev_uart.bytesize, _dev_uart.parity, _dev_uart.stopbits, 0))) {
        LOG_E("dev_uart set serial error, code is: %d.\n", ret);
        return ret;
    }
    LOG_D("dev_uart:\"%s\",%d,%d, '%c',%d. create slave.", _dev_uart.devname, _dev_uart.baudrate,
            _dev_uart.bytesize, _dev_uart.parity, _dev_uart.stopbits);
    if(MODBUS_RT_EOK != (ret = modbus_rtu_set_p2p_flag(_dev_uart.dev, 1))) {
        LOG_E("dev_uart set p2p flag error, code is: %d.\n", ret);
        return ret;
    }
    LOG_D("dev_uart set p2p flag:%d.", 1);
    if(MODBUS_RT_EOK != (ret = modbus_rtu_set_dev_binding(_dev_uart.dev, 1))) {
        LOG_E("dev_uart set_dev_binding error, code is: %d.", ret);
        return ret;
    }
    LOG_D("dev_uart set set dev_binding:%d.", 1);
    if(MODBUS_RT_EOK != (ret = modbus_rtu_set_addr(_dev_uart.dev, 1))) {
        LOG_E("dev_uart set addr error, code is: %d.\n", ret);
        return ret;
    }
    LOG_D("dev_uart set slave addr:%d.", 1);
    if(MODBUS_RT_EOK != (ret = modbus_rtu_open(_dev_uart.dev))) {
        LOG_E("dev_uart open error, code is: %d.\n", ret);
        return ret;
    }
    LOG_D("dev_uart open sucess.");
    return 0;
}
INIT_APP_EXPORT(dev_uart_init);
